import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/counter'
import { menuConfig, filterMenuByPermissions, getAllMenuPaths, findMenuByPath, type MenuItem } from '@/config/menu'

export function useMenu() {
  const route = useRoute()
  const userStore = useUserStore()

  // 根据用户权限过滤菜单
  const filteredMenus = computed(() => {
    const userPermissions = userStore.permissions || []
    const userRoles = userStore.userInfo?.roles || []
    return filterMenuByPermissions(menuConfig, userPermissions, userRoles)
  })

  // 动态生成的菜单路径映射
  const menuPathMap = computed(() => getAllMenuPaths(filteredMenus.value))

  // 当前激活的菜单
  const activeMenu = computed(() => route.path)

  // 面包屑导航
  const breadcrumbs = computed(() => {
    const path = route.path
    const pathTitles = menuPathMap.value[path]
    
    if (pathTitles && pathTitles.length > 0) {
      return pathTitles.map((title, index) => ({
        title,
        path: index === pathTitles.length - 1 ? path : ''
      }))
    }
    
    return [{ title: route.meta.title || '未知页面', path }]
  })

  // 根据路径查找菜单项
  const findMenu = (path: string): MenuItem | null => {
    return findMenuByPath(filteredMenus.value, path)
  }

  // 检查用户是否有访问某个菜单的权限
  const hasMenuPermission = (menuItem: MenuItem): boolean => {
    const userPermissions = userStore.permissions || []
    const userRoles = userStore.userInfo?.roles || []

    // 检查角色权限
    if (menuItem.roles && menuItem.roles.length > 0) {
      const hasRole = menuItem.roles.some(role => userRoles.includes(role))
      if (!hasRole) return false
    }

    // 检查具体权限
    if (menuItem.permissions && menuItem.permissions.length > 0) {
      const hasPermission = menuItem.permissions.some(permission => userPermissions.includes(permission))
      if (!hasPermission) return false
    }

    return true
  }

  // 获取当前页面的菜单信息
  const currentMenu = computed(() => {
    return findMenu(route.path)
  })

  // 获取所有可访问的菜单路径
  const accessiblePaths = computed(() => {
    const paths: string[] = []
    
    function collectPaths(menus: MenuItem[]) {
      menus.forEach(menu => {
        if (menu.path) {
          paths.push(menu.path)
        }
        if (menu.children && menu.children.length > 0) {
          collectPaths(menu.children)
        }
      })
    }
    
    collectPaths(filteredMenus.value)
    return paths
  })

  return {
    filteredMenus,
    menuPathMap,
    activeMenu,
    breadcrumbs,
    findMenu,
    hasMenuPermission,
    currentMenu,
    accessiblePaths
  }
}
